package com.quanyan.search.service.impl;


import com.alibaba.dubbo.common.json.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.SearchConstants;
import com.quanyan.common.utils.Configure;
import com.quanyan.common.utils.DistanceUtil;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.search.entity.request.ReqPlaceSearchInfo;
import com.quanyan.search.entity.request.ReqPlaceSearchInfoNew;
import com.quanyan.search.entity.response.PlaceSearchResponse;
import com.quanyan.search.entity.response.SearchResponses;
import com.quanyan.search.entity.vo.PlaceIndexInfo;
import com.quanyan.search.service.PlaceSearchService;
import com.quanyan.search.utils.CommonUtil;
import com.quanyan.search.utils.SolrServerSingle;
import org.apache.commons.collections.CollectionUtils;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.MapSolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;


/**
 * PlaceSearchServiceImpl
 * 搜索服务实现
 *
 * @author Tu Chun
 * @date 2016/6/3
 */
@Service("placeSearchService")
public class PlaceSearchServiceImpl implements PlaceSearchService {
    private static Logger logger = LoggerFactory.getLogger(PlaceSearchServiceImpl.class);
    //public final static String URL = "http://192.168.30.181:8080/solr";
    //public final static String URL = "192.168.30.181:2181,192.168.30.181:2182,192.168.30.181:2183";
    //public   static String URL = "192.168.30.75:2181,192.168.30.75:2182,192.168.30.75:2183";
    private String URL;

    public String getURL() {
        return URL;
    }

    public void setURL(String URL) {
        this.URL = URL;
    }

/*//    @Autowired
    private SearchPlaceDisplayMapper searchPlaceDisplayMapper;

//    public List<PlaceIndexInfo> getPlaceIndexInfoList() {
//        List<PlaceIndexInfo> docs = searchPlaceDisplayMapper.importAllDoc();
//        return docs;
//    }*/

    public PlaceSearchServiceImpl(String url) {
        this.URL = url;
    }

    public PlaceSearchServiceImpl() {
    }


    /**
     * 添加场馆索引
     *
     * @param insertPlaceIndexInfo
     * @return
     */
    @Override
    public APIResponse insertDoc(PlaceIndexInfo insertPlaceIndexInfo) {
        try {
            if (addDocUtil(insertPlaceIndexInfo)) {
                return APIResponse.returnSuccess("添加场馆" + insertPlaceIndexInfo.getPlace_name() + "索引c成功");
            } else {
                return APIResponse.returnFail("添加场馆索引失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加场馆索引失败", e);
            return APIResponse.returnFail("添加场馆索引失败");
        }
    }

    /**
     * 批量添加多个场馆索引
     *
     * @param insertPlaceIndexInfos
     * @return
     */
    @Override
    public APIResponse insertDocs(final List<PlaceIndexInfo> insertPlaceIndexInfos) {

        try {
            Long startTime = System.currentTimeMillis();
            Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
            Integer placeSubmitNum = Integer.parseInt(Configure.getPropertyBykey("place_submitNum")) * 10000;
            //提交的次数
            int submitConunt = 0;
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            for (int i = 0; i < insertPlaceIndexInfos.size(); i++) {

                PlaceIndexInfo indexInfo = insertPlaceIndexInfos.get(i);
                //创建文档对象
                SolrInputDocument document = new SolrInputDocument();
                String uniqueId = SearchConstants.PLACE_ID_PREFIX + UUID.randomUUID().toString();
                document.addField("id", uniqueId);
                document.addField("place_id", indexInfo.getPlace_id());
                document.addField("place_name", indexInfo.getPlace_name());
                List<Integer> categoryIds = indexInfo.getPlace_categoryId();
                List<String> categoryNames = indexInfo.getPlace_categoryName();
                if (CollectionUtils.isNotEmpty(categoryIds)) {
                    for (int j = 0; j < categoryIds.size(); j++) {
                        document.addField("place_categoryId", categoryIds.get(j));
                    }
                }
                if (CollectionUtils.isNotEmpty(categoryNames)) {
                    for (int j = 0; j < categoryIds.size(); j++) {
                        document.addField("place_categoryName", categoryNames.get(j));
                    }
                }
                document.addField("place_categoryIdSingle", indexInfo.getPlace_categoryIdSingle());
                document.addField("place_cityId", indexInfo.getPlace_cityId());
                document.addField("place_cityName", indexInfo.getPlace_cityName());
                document.addField("place_districtId", indexInfo.getPlace_districtId());
                document.addField("place_districtName", indexInfo.getPlace_districtName());
                document.addField("place_latlng", indexInfo.getPlace_lat() + "," + indexInfo.getPlace_lng());
                document.addField("place_commentCount", indexInfo.getPlace_commentCount());
                document.addField("place_signupCount", indexInfo.getPlace_signupCount());
                if (indexInfo.getPlace_lowestPrice() == null) {
                    document.addField("place_lowestPrice", -1.00);//如果没有价格就存-1 用于价格排序
                } else {
                    document.addField("place_lowestPrice", indexInfo.getPlace_lowestPrice());
                }
                document.addField("place_placeScore", indexInfo.getPlace_placeScore());
                document.addField("place_bizPlaceUrl", indexInfo.getPlace_bizPlaceUrl());
                document.addField("place_isSigned", indexInfo.getPlace_isSigned());
                document.addField("place_phone", indexInfo.getPlace_phone());
                document.addField("place_address", indexInfo.getPlace_address());
                if (!StringUtil.isBlankOrNull(indexInfo.getPlace_salePlanId()) && !"0".equals(indexInfo.getPlace_salePlanId()))
                    document.addField("place_salePlanId", indexInfo.getPlace_salePlanId());
                if (indexInfo.getPlace_startTime() != null)
                    document.addField("place_startTime", CommonUtil.getSolrDate(indexInfo.getPlace_startTime()));
                if (indexInfo.getPlace_endTime() != null)
                    document.addField("place_endTime", CommonUtil.getSolrDate(indexInfo.getPlace_endTime()));
                document.addField("place_isSaled", indexInfo.getPlace_isSaled());
                document.addField("place_groupId", indexInfo.getPlace_groupId());
                List<String> initialsList = indexInfo.getPlace_initials();
                if (CollectionUtils.isNotEmpty(initialsList)) {
                    for (int k = 0; k < initialsList.size(); k++) {
                        document.addField("place_initials", initialsList.get(k));
                    }
                }
                document.addField("place_isVip", indexInfo.getPlace_isVip());
                //1上架  0下架  不传全包含
                document.addField("place_isShelves", indexInfo.getPlace_isShelves());
                docs.add(document);
                //logger.warn("添加" + (i+1) + "号索引到文档中");
                if ((i + 1) % placeSubmitNum == 0) {
                    solrServer.add(docs);
                    solrServer.commit();
                    long endTime = System.currentTimeMillis();
                    logger.warn("第" + ++submitConunt + "次添加" + (i + 1) + "条索引已执行时间：" + ((endTime - startTime) / (60 * 1000)) + "分钟.");
                    //清空集合
                    docs.clear();

                }

            }
            solrServer.add(docs);
            solrServer.commit();
            Long endTime = System.currentTimeMillis();
            logger.warn("第" + ++submitConunt + "次添加" + insertPlaceIndexInfos.size() + "条索引已执行时间：" + ((endTime - startTime) / (60 * 1000)) + "分钟.");
            logger.warn("添加多个场馆索引成功");
            return APIResponse.returnSuccess("添加多个场馆索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加多个场馆索引异常", e);
            return APIResponse.returnFail("添加多个场馆索引失败");
        }

    }
  /*  *//**
     * 添加多个场馆索引
     *
     * @param insertPlaceIndexInfos
     * @return
     *//*
    @Override
    public APIResponse insertDocs(final List<PlaceIndexInfo> insertPlaceIndexInfos) {
        ExecutorService executorService = Executors.newFixedThreadPool(Constant.THREADNUM);
        try {
            for (int i = 0; i < insertPlaceIndexInfos.size(); i++) {
                final int index = i;
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        logger.warn("当前线程："+Thread.currentThread().getName()+"执行第"+index+"命令");
                        PlaceIndexInfo insertPlaceIndexInfo = insertPlaceIndexInfos.get(index);
                        addDocUtil(insertPlaceIndexInfo);
                    }
                });
            }
            return APIResponse.returnSuccess("添加多个场馆索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加多个场馆索引异常", e);
            return APIResponse.returnFail("添加多个场馆索引失败");
        }

    }*/

    /**
     * 删除所有Document
     *
     * @param type 1 销售计划id 2 场馆id
     * @return
     */
    @Override
    public APIResponse deleteAllDoc(Integer type) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            StringBuilder stringBuilder = new StringBuilder();
            if (type == 1) {
                stringBuilder.append("place_salePlanId:*");
            } else if (type == 2) {
                stringBuilder.append("place_id:*");
            }
            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();
            return APIResponse.returnSuccess("删除所有场馆索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "删除所有场馆索引异常", e);
            return APIResponse.returnFail("删除所有场馆索引失败");
        }
    }

    /**
     * 根据id删除Document
     *
     * @param type            1 销售计划id 2 场馆id
     * @param placeSalePlanId
     * @return
     */
    @Override
    public APIResponse deleteDocById(Integer placeSalePlanId, Integer type) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            StringBuilder stringBuilder = new StringBuilder();
            if (CommonUtil.isNullOrZero(placeSalePlanId)) {
                return APIResponse.returnFail("场馆售卖计划id不能为空");
            } else if (!CommonUtil.isNullOrZero(placeSalePlanId)) {
                if (type == 1) {
                    stringBuilder.append("place_salePlanId:").append(placeSalePlanId);
                } else if (type == 2) {
                    stringBuilder.append("place_id:").append(placeSalePlanId);
                }
            }

            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();
            return APIResponse.returnSuccess("删除场馆索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "删除场馆索引异常", e);
            return APIResponse.returnFail("删除场馆索引失败");
        }
    }


    /**
     * 删除多个Document
     *
     * @param type             1 销售计划id 2 场馆id
     * @param placeSalePlanIds
     * @return
     */
    @Override
    public APIResponse deleteDocsByIds(List<Integer> placeSalePlanIds, Integer type) {
        Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
        //创建连接
        CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
        // 设置默认的collection
        solrServer.setDefaultCollection("collection2");
        try {
            if (CommonUtil.isNullOrZero(placeSalePlanIds)) {
                return APIResponse.returnFail("场馆售卖计划ids不能为空");
            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("place_salePlanId:(");
            //记录开始下标
            int flag = 0;
            for (int i = 0; i < placeSalePlanIds.size(); i++) {

                Integer id = placeSalePlanIds.get(i);
                if (type == 1) {
                    if (i == flag) {
                        stringBuilder.append(id);
                    } else {
                        stringBuilder.append(" OR ").append(id);
                    }
                } else if (type == 2) {
                    if (i == flag) {
                        stringBuilder.append(id);
                    } else {
                        stringBuilder.append(" OR ").append(id);
                    }
                }
                if (i % 1000 == 0 && i != 0) {
                    stringBuilder.append(")");
                    //logger.warn("批量删除条件：" + stringBuilder.toString());
                    solrServer.deleteByQuery(stringBuilder.toString());
                    solrServer.commit(false, false);
                    //将提交的清空
                    stringBuilder.delete(0, stringBuilder.length());
                    flag = i + 1;
                    stringBuilder.append("place_salePlanId:(");
                }
            }
            stringBuilder.append(")");
            //logger.warn("批量删除条件：" + stringBuilder.toString());
            //提交剩余内容
            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit(false, false);
            return APIResponse.returnSuccess("删除多个场馆索引成功");

        } catch (Exception e) {
            logger.error(e.getMessage() + "删除多个场馆索引异常", e);
            return APIResponse.returnFail("删除多个场馆索引失败");
        }


    }


    /**
     * 根据id获取场馆信息
     *
     * @param placeSalePlanId
     * @return
     */
    @Override
    public APIResponse<PlaceIndexInfo> searchPlaceInfo(Integer placeSalePlanId, Integer type) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            StringBuilder builder = new StringBuilder();
            if (CommonUtil.isNullOrZero(placeSalePlanId)) {
                return APIResponse.returnFail("场馆售卖计划id不能为空");
            } else if (!CommonUtil.isNullOrZero(placeSalePlanId)) {
                if (type == 1) {
                    builder.append("place_salePlanId:").append(placeSalePlanId);
                } else if (type == 2) {
                    builder.append("place_id:").append(placeSalePlanId);
                }
            }
            params.put("q", builder.toString());
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
            return APIResponse.returnSuccess(CommonUtil.isNullOrZero(placeIndexInfoList) ? null : placeIndexInfoList.get(0));
        } catch (Exception e) {
            logger.error(e.getMessage() + "根据id搜索场馆异常", e);
            return APIResponse.returnFail("根据id搜索场馆失败");
        }
    }

    /**
     * 根据场馆ids查找场馆
     *
     * @param placeIds
     * @return
     */
    @Override
    public APIResponse<List<PlaceSearchResponse>> searchPlaceInfoByPlaceIds(List<Integer> placeIds) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            StringBuilder builder = new StringBuilder();
            if (placeIds == null || placeIds.size() <= 0) {
                return APIResponse.returnFail(null,"场馆ids为空");
            }
            builder.append("place_id:").append("(");
            for (int i = 0; i < placeIds.size(); i++) {
                if (i == placeIds.size() - 1) {
                    builder.append("place_id:").append(placeIds.get(i) + ")");
                }else{
                    builder.append("place_id:").append(placeIds.get(i) + " OR ");
                }

            }
            params.put("q", builder.toString());
            params.put("group", "true");
            params.put("group.field", "place_id");
            params.put("group.limit", "1");
            params.put("group.main", "true");
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
            List<PlaceSearchResponse> placeResList = getPlaceSearchResponseList(solrDocumentList, null);
            return APIResponse.returnSuccess(placeResList);
        } catch (Exception e) {
            logger.error(e.getMessage() + "根据场馆ids搜索场馆异常", e);
            return APIResponse.returnFail("根据场馆ids搜索场馆失败");
        }
    }

    /**
     * 查询场馆14天前的数据
     *
     * @return
     */
    @Override
    public APIResponse<List<PlaceIndexInfo>> searchPlaceInfoBefore14Day() {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            StringBuilder builder = new StringBuilder();

            builder.append("place_endTime:").append("[NOW/DAY-14DAY TO NOW]");

            params.put("q", builder.toString());
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
            logger.warn("14天前的数据：" + JSON.json(placeIndexInfoList));
            return APIResponse.returnSuccess(placeIndexInfoList);
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索场馆14天前数据异常", e);
            return APIResponse.returnFail("搜索场馆14天前数据异常");
        }
    }

    /**
     * 根据条件搜索 新
     * 用户已经订的场馆优先显示
     *
     * @param reqPlaceSearchInfo
     * @return
     */
    @Override
    public APIResponse<SearchResponses<List<PlaceSearchResponse>>> searchPlaceInfoListNew(ReqPlaceSearchInfoNew reqPlaceSearchInfo) {
        try {
            Integer pageNo = reqPlaceSearchInfo.getPageNo();
            Integer pageSize = reqPlaceSearchInfo.getPageSize();
            List<Integer> placeIds = reqPlaceSearchInfo.getPlaceIds();
            if (placeIds != null && placeIds.size() > 0) {
                Integer placeIdsSize = placeIds.size();

                if (placeIdsSize < pageSize) {
                    //用户已经订场馆数小于一页大小
                    if (pageNo == 0) {
                        List<PlaceSearchResponse> placeSearchResponses = searchPlaceInfoByPlaceIds(placeIds).getData();
                        reqPlaceSearchInfo.setPageSize(pageSize - placeIdsSize);
                        placeSearchResponses.addAll(getPlaceSearchResponseByConditin(reqPlaceSearchInfo));
                        SearchResponses<List<PlaceSearchResponse>> searchResponses = new SearchResponses();
                        searchResponses.setPageSize(pageSize);
                        searchResponses.setPageNo(pageNo);
                        searchResponses.setPageStart(pageSize - placeIdsSize);
                        searchResponses.setData(placeSearchResponses);
                        return APIResponse.returnSuccess(searchResponses);
                    } else {
                        List<PlaceSearchResponse> placeSearchResponses=getPlaceSearchResponseByConditin(reqPlaceSearchInfo);
                        SearchResponses<List<PlaceSearchResponse>> searchResponses = new SearchResponses();
                        searchResponses.setPageSize(pageSize);
                        searchResponses.setPageNo(pageNo);
                        searchResponses.setPageStart(reqPlaceSearchInfo.getStartPosition()+pageSize);
                        searchResponses.setData(placeSearchResponses);
                        return APIResponse.returnSuccess(searchResponses);
                    }
                } else {
                    //用户已经订场馆数大于等于一页大小
                    //余数
                    int a=placeIdsSize%pageSize;
                    //倍数
                    int b=placeIdsSize/pageSize;
                    if (pageNo <= b) {
                        List<PlaceSearchResponse> placeSearchResponses = searchPlaceInfoByPlaceIds(placeIds.subList(pageNo * pageSize, (pageNo + 1) * pageSize)).getData();
                        SearchResponses<List<PlaceSearchResponse>> searchResponses = new SearchResponses();
                        searchResponses.setPageSize(pageSize);
                        searchResponses.setPageNo(pageNo);
                        searchResponses.setPageStart(pageNo * pageSize);
                        searchResponses.setData(placeSearchResponses);
                        return APIResponse.returnSuccess(searchResponses);
                    } else {
                        if (pageNo == b + 1) {
                            List<PlaceSearchResponse> placeSearchResponses = searchPlaceInfoByPlaceIds(placeIds.subList(pageNo * pageSize, pageNo * pageSize + a)).getData();
                            reqPlaceSearchInfo.setPageSize(pageSize - a);
                            reqPlaceSearchInfo.setStartPosition(0);
                            placeSearchResponses.addAll(getPlaceSearchResponseByConditin(reqPlaceSearchInfo));
                            SearchResponses<List<PlaceSearchResponse>> searchResponses = new SearchResponses();
                            searchResponses.setPageSize(pageSize);
                            searchResponses.setPageNo(pageNo);
                            searchResponses.setPageStart(pageSize - a);
                            searchResponses.setData(placeSearchResponses);
                            return APIResponse.returnSuccess(searchResponses);
                        } else {
                            List<PlaceSearchResponse> placeSearchResponses=getPlaceSearchResponseByConditin(reqPlaceSearchInfo);
                            SearchResponses<List<PlaceSearchResponse>> searchResponses = new SearchResponses();
                            searchResponses.setPageSize(pageSize);
                            searchResponses.setPageNo(pageNo);
                            searchResponses.setPageStart(reqPlaceSearchInfo.getStartPosition()+pageSize);
                            searchResponses.setData(placeSearchResponses);
                            return APIResponse.returnSuccess(searchResponses);
                        }

                    }
                }
            }

          /*  searchResponses.setData(placeResList);
            searchResponses.setPageNo(pageNo);
            searchResponses.setPageSize(pageSize);
            searchResponses.setTotal((int) total);*/
            return APIResponse.returnFail("没有数据");
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索数据异常", e);
            return APIResponse.returnFail("搜索数据异常");
        }
    }
    private List<PlaceSearchResponse> getPlaceSearchResponseByConditin(ReqPlaceSearchInfoNew reqPlaceSearchInfo) throws Exception {
        SearchResponses<List<PlaceSearchResponse>> searchResponses = new SearchResponses<List<PlaceSearchResponse>>();
        //创建连接
        CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
        // 设置默认的collection
        solrServer.setDefaultCollection("collection2");
        Map<String, String> params = new HashMap<String, String>();
        Integer pageNo = reqPlaceSearchInfo.getPageNo();
        Integer pageSize = reqPlaceSearchInfo.getPageSize();
        String placeKeyName = reqPlaceSearchInfo.getPlaceKeyName();
        Integer cityId = reqPlaceSearchInfo.getCityId();
        Integer districtId = reqPlaceSearchInfo.getDistrictId();
        Integer categoryId = reqPlaceSearchInfo.getCategoryId();
        Integer sortType = reqPlaceSearchInfo.getSortId();
        Integer isSigned = reqPlaceSearchInfo.getIsSigned();
        Double distance = reqPlaceSearchInfo.getDistance();
        Integer isVip = reqPlaceSearchInfo.getIsVip();
        //1上架  2下架  不传全包含
        Integer isShelves = reqPlaceSearchInfo.getIsShelves();
        //1 不可售卖 2 可以售卖 0没有销售计划
        Integer isSaled = reqPlaceSearchInfo.getIsSaled();
        //搜索类型 0 按照用户定位的位置搜索 1 按照地图拖动的位置搜索
        Integer searchType = 0;
        String date = reqPlaceSearchInfo.getDate();
        List<String> startTimeList = new ArrayList<String>();
        List<String> endTimeList = new ArrayList<String>();

        if (!CommonUtil.isNullOrZero(reqPlaceSearchInfo.getStartTimeList())) {
            startTimeList = reqPlaceSearchInfo.getStartTimeList();
        }
        if (!CommonUtil.isNullOrZero(reqPlaceSearchInfo.getEndTimeList())) {
            endTimeList = reqPlaceSearchInfo.getEndTimeList();
        }


        Double lat = reqPlaceSearchInfo.getLat();
        Double lng = reqPlaceSearchInfo.getLng();

        Double currentLat = reqPlaceSearchInfo.getCurrentLat();
        Double currentLng = reqPlaceSearchInfo.getCurrentLng();
        Integer startPosition=0;
        if (pageNo == 0) {
            startPosition = pageNo * pageSize;//首页为0
        } else {
            startPosition=reqPlaceSearchInfo.getStartPosition();
        }

        StringBuilder builder = new StringBuilder();

        if (!StringUtil.isBlankOrNull(date) && !CommonUtil.isNullOrZero(startTimeList))
            builder.append("(");
        builder.append("place_lowestPrice:").append("[0 TO *]");
        //排除下过订单的场馆  place_id:(* NOT 35990 NOT 35991)
        List<Integer> placeIds=reqPlaceSearchInfo.getPlaceIds();
        if (!placeIds.isEmpty()) {
            builder.append(" AND place_id:").append("(* ");
            for (Integer placeId : placeIds) {
                builder.append(" NOT "+placeId);
            }
            builder.append(" )");
        }
            /*  //1 不可售卖 2 可以售卖 0没有销售计划 3 活动售卖
            if (isSaled != 3)
                builder.append("AND place_isSaled:").append(isSaled);*/
        //1上架  2下架  不传全包含
        if (!CommonUtil.isNullOrZero(isShelves)) {
            builder.append(" AND place_isShelves:").append(isShelves);
        }

        if (!CommonUtil.isNullOrZero(cityId))
            builder.append(" AND place_cityId:").append(cityId);

        if (!StringUtil.isBlankOrNull(placeKeyName)) {
            //场馆名加权重
            builder.append(" AND (place_name:").append(placeKeyName + "^1.9");
            builder.append(" OR place_initials:").append(placeKeyName + "^1.9)");
        }
        if (!CommonUtil.isNullOrZero(districtId)) {
            builder.append(" AND place_districtId:").append(districtId);
        }
        if (isVip != null) {
            builder.append(" AND place_isVip:").append(isVip);
        }
        if (isSigned != null) {
            builder.append(" AND place_isSigned:").append(isSigned);
            if (isSigned == 1) {//有签约categoryId查place_categoryIdSingle
                if (!CommonUtil.isNullOrZero(categoryId)) {
                    builder.append(" AND place_categoryIdSingle:").append(categoryId);
                }
                //1 不可售卖 2 可以售卖 0没有销售计划 3 活动售卖
//                builder.append(" AND place_isSaled:").append(isSaled);
            } else if (isSigned == 0) {//没有签约categoryId查place_categoryId
                if (!CommonUtil.isNullOrZero(categoryId)) {
                    builder.append(" AND place_categoryId:").append(categoryId);
                }
            }
        } else {
            if (!CommonUtil.isNullOrZero(categoryId)) {
                builder.append(" AND place_categoryId:").append(categoryId);
            }
        }
        String temp = builder.toString();
        if (!StringUtil.isBlankOrNull(date) && !CommonUtil.isNullOrZero(startTimeList)) {


            for (int i = 0; i < startTimeList.size(); i++) {
                String startTime = CommonUtil.getSolrDate(date + " " + startTimeList.get(i));
                //String endTime = CommonUtil.getSolrDate(date + " " + endTimeList.get(i));
                if (i == 0) {
                    builder.append(" AND place_startTime:").append(CommonUtil.getSolrDateScope3(startTime, startTime));
                    builder.append(")");
                    continue;
                }

                builder.append(" OR ").append(temp);
                builder.append(" AND place_startTime:").append(CommonUtil.getSolrDateScope3(startTime, startTime));
                builder.append(")");
            }

        }
        if ((!StringUtil.isBlankOrNull(date) && CommonUtil.isNullOrZero(startTimeList)) || (!StringUtil.isBlankOrNull(date) && "00:00:00".equals(startTimeList.get(0)) && "24:00:00".equals(endTimeList.get(0)))) {
            builder.append(" AND place_startTime:").append(CommonUtil.getSolrDateScope(date));
        }
        logger.warn("query:" + builder.toString());
        params.put("q", builder.toString());
        params.put("fq", "{!geofilt}");//距离过滤函数
        if (currentLat != null && currentLng != null) {
            searchType = 1;
            params.put("pt", CommonUtil.getLatLng(currentLat, currentLng));//当前经纬度
        } else {
            params.put("pt", CommonUtil.getLatLng(lat, lng));//当前经纬度
        }

        params.put("sfield", "place_latlng");//经纬度的字段
        params.put("d", distance.toString());
        /**
         * 排序id 1、智能排序 2、价格排序 3、离我最近 4、人气最高
         * 如果没有传值默认为1
         */

        if (!StringUtils.isEmpty(sortType) && sortType == 2) {
            params.put("sort", "place_lowestPrice asc,geodist() asc,score desc");//根据价格升序
        } else if (!StringUtils.isEmpty(sortType) && sortType == 3) {
            params.put("sort", "geodist() asc,place_lowestPrice asc,score desc");//根据距离升序
        } else if (!StringUtils.isEmpty(sortType) && sortType == 4) {
            params.put("sort", "place_signupCount desc,place_lowestPrice asc,score desc");//根据人气降序
        } else if (!StringUtils.isEmpty(sortType) && sortType == 1) {
            //根据距离升序
            //params.put("sort", "geodist() asc,place_lowestPrice asc,score desc");//根据距离升序
            //默认为智能排序
            Integer signupCount = Integer.parseInt(Configure.getPropertyBykey("place_signupCount"));
            Double lowestPrice = Double.parseDouble(Configure.getPropertyBykey("place_lowestPrice"));
            Float dist = Float.parseFloat(Configure.getPropertyBykey("place_dist"));
            params.put("defType", "edismax");
            // recip(x,m,a,b)=a/(m*x+b)其中，m、a、b是常量，x是变量或者一个函数。当a=b，并且x>=0的时候，这个函数的最大值是1，值的大小随着x的增大而减小。
            params.put("bf", "sum(div(place_signupCount," + signupCount + "),recip(place_lowestPrice,1," + lowestPrice + "," + lowestPrice + "),recip(geodist(),1," + dist + "," + dist + "))");
            params.put("sort", "score desc,place_lowestPrice asc");//根据综合评分降序*/
        }


        params.put("group", "true");
        params.put("group.field", "place_id");
        params.put("group.limit", "1");
        params.put("group.main", "true");


        params.put("fl", "*,place_dist:geodist(),score");
        params.put("start", startPosition.toString());//记录开始位置
        params.put("rows", pageSize.toString());//查询的行数
        params.put("df", "place_keywords");   // 设置默认搜索域
        //设置高亮
           /* params.put("hl", "true");
            params.put("hl.fl", "place_name");
            params.put("hl.simple.pre", "<em style=\"color:red\">");
            params.put("hl.simple.post", "</em>");*/

        params.put("shards.tolerant", "true");
        logger.warn("params:" + JSON.json(params));
        QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
        logger.warn(response.getResults().toString());
        SolrDocumentList solrDocumentList = response.getResults();

        long total = solrDocumentList.getNumFound();
        //long total = solrDocumentList.size();
        logger.warn(total + "");
        //取高亮显示
        //Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

        //List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
        List<PlaceSearchResponse> placeResList = getPlaceSearchResponseList(solrDocumentList, null);
        return placeResList;
    }
    /**
     * 根据条件搜索
     *
     * @param reqPlaceSearchInfo
     * @return
     */
    @Override
    public APIResponse<SearchResponses<List<PlaceSearchResponse>>> searchPlaceInfoList(ReqPlaceSearchInfo reqPlaceSearchInfo) {
        try {
            SearchResponses<List<PlaceSearchResponse>> searchResponses = new SearchResponses<List<PlaceSearchResponse>>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            String placeKeyName = reqPlaceSearchInfo.getPlaceKeyName();
            Integer cityId = reqPlaceSearchInfo.getCityId();
            Integer districtId = reqPlaceSearchInfo.getDistrictId();
            Integer categoryId = reqPlaceSearchInfo.getCategoryId();
            Integer sortType = reqPlaceSearchInfo.getSortId();
            Integer isSigned = reqPlaceSearchInfo.getIsSigned();
            Double distance = reqPlaceSearchInfo.getDistance();
            Integer isVip = reqPlaceSearchInfo.getIsVip();
            //1上架  2下架  不传全包含
            Integer isShelves = reqPlaceSearchInfo.getIsShelves();
            //1 不可售卖 2 可以售卖 0没有销售计划
            Integer isSaled = reqPlaceSearchInfo.getIsSaled();
            //搜索类型 0 按照用户定位的位置搜索 1 按照地图拖动的位置搜索
            Integer searchType = 0;
            String date = reqPlaceSearchInfo.getDate();
            List<String> startTimeList = new ArrayList<String>();
            List<String> endTimeList = new ArrayList<String>();

            if (!CommonUtil.isNullOrZero(reqPlaceSearchInfo.getStartTimeList())) {
                startTimeList = reqPlaceSearchInfo.getStartTimeList();
            }
            if (!CommonUtil.isNullOrZero(reqPlaceSearchInfo.getEndTimeList())) {
                endTimeList = reqPlaceSearchInfo.getEndTimeList();
            }


            Double lat = reqPlaceSearchInfo.getLat();
            Double lng = reqPlaceSearchInfo.getLng();

            Double currentLat = reqPlaceSearchInfo.getCurrentLat();
            Double currentLng = reqPlaceSearchInfo.getCurrentLng();
            Integer pageNo = reqPlaceSearchInfo.getPageNo();
            Integer pageSize = reqPlaceSearchInfo.getPageSize();
            Integer startPosition = pageNo * pageSize;//首页为0
            StringBuilder builder = new StringBuilder();

            if (!StringUtil.isBlankOrNull(date) && !CommonUtil.isNullOrZero(startTimeList))
                builder.append("(");
            builder.append("place_lowestPrice:").append("[0 TO *]");
            /*  //1 不可售卖 2 可以售卖 0没有销售计划 3 活动售卖
            if (isSaled != 3)
                builder.append("AND place_isSaled:").append(isSaled);*/
            //1上架  2下架  不传全包含
            if (!CommonUtil.isNullOrZero(isShelves)) {
                builder.append(" AND place_isShelves:").append(isShelves);
            }

            if (!CommonUtil.isNullOrZero(cityId))
                builder.append(" AND place_cityId:").append(cityId);

            if (!StringUtil.isBlankOrNull(placeKeyName)) {
                //场馆名加权重
                builder.append(" AND (place_name:").append(placeKeyName + "^1.9");
                builder.append(" OR place_initials:").append(placeKeyName + "^1.9)");
            }
            if (!CommonUtil.isNullOrZero(districtId)) {
                builder.append(" AND place_districtId:").append(districtId);
            }
            if (isVip != null) {
                builder.append(" AND place_isVip:").append(isVip);
            }
            if (isSigned != null) {
                builder.append(" AND place_isSigned:").append(isSigned);
                if (isSigned == 1) {//有签约categoryId查place_categoryIdSingle
                    if (!CommonUtil.isNullOrZero(categoryId)) {
                        builder.append(" AND place_categoryIdSingle:").append(categoryId);
                    }
                    //1 不可售卖 2 可以售卖 0没有销售计划 3 活动售卖
//                    builder.append(" AND place_isSaled:").append(isSaled);
                } else if (isSigned == 0) {//没有签约categoryId查place_categoryId
                    if (!CommonUtil.isNullOrZero(categoryId)) {
                        builder.append(" AND place_categoryId:").append(categoryId);
                    }
                }
            } else {
                if (!CommonUtil.isNullOrZero(categoryId)) {
                    builder.append(" AND place_categoryId:").append(categoryId);
                }
            }
            String temp = builder.toString();
            if (!StringUtil.isBlankOrNull(date) && !CommonUtil.isNullOrZero(startTimeList)) {


                for (int i = 0; i < startTimeList.size(); i++) {
                    String startTime = CommonUtil.getSolrDate(date + " " + startTimeList.get(i));
                    //String endTime = CommonUtil.getSolrDate(date + " " + endTimeList.get(i));
                    if (i == 0) {
                        builder.append(" AND place_startTime:").append(CommonUtil.getSolrDateScope3(startTime, startTime));
                        builder.append(" AND place_isSaled:").append(2);
                        builder.append(")");
                        continue;
                    }

                    builder.append(" OR ").append(temp);
                    builder.append(" AND place_startTime:").append(CommonUtil.getSolrDateScope3(startTime, startTime));
                    builder.append(" AND place_isSaled:").append(2);
                    builder.append(")");
                }

            }
            if ((!StringUtil.isBlankOrNull(date) && CommonUtil.isNullOrZero(startTimeList)) || (!StringUtil.isBlankOrNull(date) && "00:00:00".equals(startTimeList.get(0)) && "24:00:00".equals(endTimeList.get(0)))) {
                builder.append(" AND place_startTime:").append(CommonUtil.getSolrDateScope(date));
                builder.append(" AND place_isSaled:").append(2);
            }
            logger.warn("query:" + builder.toString());
            params.put("q", builder.toString());
            params.put("fq", "{!geofilt}");//距离过滤函数
            if (currentLat != null && currentLng != null) {
                searchType = 1;
                params.put("pt", CommonUtil.getLatLng(currentLat, currentLng));//当前经纬度
            } else {
                params.put("pt", CommonUtil.getLatLng(lat, lng));//当前经纬度
            }

            params.put("sfield", "place_latlng");//经纬度的字段
            params.put("d", distance.toString());
            /**
             * 排序id 1、智能排序 2、价格排序 3、离我最近 4、人气最高
             * 如果没有传值默认为1
             */

            if (!StringUtils.isEmpty(sortType) && sortType == 2) {
                params.put("sort", "place_lowestPrice asc,geodist() asc,score desc");//根据价格升序
            } else if (!StringUtils.isEmpty(sortType) && sortType == 3) {
                params.put("sort", "geodist() asc,place_lowestPrice asc,score desc");//根据距离升序
            } else if (!StringUtils.isEmpty(sortType) && sortType == 4) {
                params.put("sort", "place_signupCount desc,place_lowestPrice asc,score desc");//根据人气降序
            } else if (!StringUtils.isEmpty(sortType) && sortType == 1) {
                //根据距离升序
                params.put("sort", "geodist() asc,place_lowestPrice asc,score desc");//根据距离升序
               /* //params.put("sort", "geodist() asc,place_lowestPrice asc,score desc");//根据距离升序
                //默认为智能排序
                Integer signupCount = Integer.parseInt(Configure.getPropertyBykey("place_signupCount"));
                Double lowestPrice = Double.parseDouble(Configure.getPropertyBykey("place_lowestPrice"));
                Float dist = Float.parseFloat(Configure.getPropertyBykey("place_dist"));
                params.put("defType", "edismax");
                // recip(x,m,a,b)=a/(m*x+b)其中，m、a、b是常量，x是变量或者一个函数。当a=b，并且x>=0的时候，这个函数的最大值是1，值的大小随着x的增大而减小。
                params.put("bf", "sum(div(place_signupCount," + signupCount + "),recip(place_lowestPrice,1," + lowestPrice + "," + lowestPrice + "),recip(geodist(),1," + dist + "," + dist + "))");
                params.put("sort", "score desc,place_lowestPrice asc");//根据综合评分降序*/
            }


            params.put("group", "true");
            params.put("group.field", "place_id");
            params.put("group.limit", "1");
            params.put("group.main", "true");


            params.put("fl", "*,place_dist:geodist(),score");
            params.put("start", startPosition.toString());//记录开始位置
            params.put("rows", pageSize.toString());//查询的行数
            params.put("df", "place_keywords");   // 设置默认搜索域
            //设置高亮
           /* params.put("hl", "true");
            params.put("hl.fl", "place_name");
            params.put("hl.simple.pre", "<em style=\"color:red\">");
            params.put("hl.simple.post", "</em>");*/

            params.put("shards.tolerant", "true");
            logger.warn("place_params:" + JSON.json(params));
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            logger.warn(response.getResults().toString());
            SolrDocumentList solrDocumentList = response.getResults();

            long total = solrDocumentList.getNumFound();
            //long total = solrDocumentList.size();
            logger.warn(total + "");
            //取高亮显示
            //Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

            //List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
            List<PlaceSearchResponse> placeResList = getPlaceSearchResponseList(solrDocumentList, null, date, startTimeList, searchType, lat, lng);

            logger.warn("placeResList-size:" + placeResList.size());
            logger.warn("placeResList:" + JSON.json(placeResList));
            searchResponses.setData(placeResList);
            searchResponses.setPageNo(pageNo);
            searchResponses.setPageSize(pageSize);
            searchResponses.setTotal((int) total);
            return APIResponse.returnSuccess(searchResponses);
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索数据异常", e);
            return APIResponse.returnFail("搜索数据异常");
        }
    }

    private List<PlaceSearchResponse> getPlaceSearchResponseList(SolrDocumentList solrDocumentList, Map<String, Map<String, List<String>>> highlighting, String date, List<String> startTimeList, Integer searchType, Double lat, Double lng) throws ParseException, IOException {
        List<PlaceSearchResponse> placeResList = new ArrayList<PlaceSearchResponse>();
        List<PlaceIndexInfo> placeIndexInfoList = new ArrayList<PlaceIndexInfo>();

        for (SolrDocument solrDocument : solrDocumentList) {
            PlaceIndexInfo pojoInfo = new PlaceIndexInfo();
            //解析solr中数据
            String id = (String) solrDocument.get("id");
            String placeId = (String) solrDocument.get("place_id");
            String placeName = (String) solrDocument.get("place_name");
            List<Integer> placeCategoryIds = (List<Integer>) solrDocument.get("place_categoryId");
            List<String> placeCategoryName = (List<String>) solrDocument.get("place_categoryName");
            Integer placeCategoryIdSingle = (Integer) solrDocument.get("place_categoryIdSingle");
            Integer placeCityId = (Integer) solrDocument.get("place_cityId");
            String placeCityName = (String) solrDocument.get("place_cityName");
            Integer placeDistrictId = (Integer) solrDocument.get("place_districtId");
            String placeDistrictName = (String) solrDocument.get("place_districtName");
            String placeLatLng = (String) solrDocument.get("place_latlng");
            Double placeLat = 0.0;
            Double placeLng = 0.0;
            if (!StringUtil.isBlankOrNull(placeLatLng)) {
                placeLat = Double.parseDouble(placeLatLng.split(",")[0]);
                placeLng = Double.parseDouble(placeLatLng.split(",")[1]);
            }

            Integer placeCommentCount = (Integer) solrDocument.get("place_commentCount");
            Integer placeSignupCount = (Integer) solrDocument.get("place_signupCount");
            Double placeLowestPrice = (Double) solrDocument.get("place_lowestPrice");
            Double placePlaceScore = (Double) solrDocument.get("place_placeScore");
            String placeBizPlaceUrl = (String) solrDocument.get("place_bizPlaceUrl");
            String placeSalePlanId = (String) solrDocument.get("place_salePlanId");
            Integer placeIsSigned = (Integer) solrDocument.get("place_isSigned");
            Date placeStartTime = (Date) solrDocument.get("place_startTime");
            Date placeEndTime = (Date) solrDocument.get("place_endTime");
            Integer placeIsSaled = (Integer) solrDocument.get("place_isSaled");
            String placeGroupId = (String) solrDocument.get("place_groupId");
            Float score = (Float) solrDocument.get("score");
            Float placeDist = (Float) solrDocument.get("place_dist");
            String placePhone = (String) solrDocument.get("place_phone");
            String placeAddress = (String) solrDocument.get("place_address");
            Integer placeIsVip = (Integer) solrDocument.get("place_isVip");
            Integer placeIsShelves = (Integer) solrDocument.get("place_isShelves");
          /*  Map<String, List<String>> stringListMap = highlighting.get(solrDocument.get("id").toString());
            List<String> list = null;*/
            //取高亮显示的结果
            /*if (stringListMap != null && stringListMap.size() > 0) {
                list = stringListMap.get("place_name");
            }
            if (list != null && list.size() > 0) {
                placeName = list.get(0);
            } else {
                placeName = (String) solrDocument.get("place_name");
            }*/

            placeStartTime = placeStartTime == null ? null : CommonUtil.getFormatDateByLong(placeStartTime.getTime());

            placeEndTime = placeEndTime == null ? null : CommonUtil.getFormatDateByLong(placeEndTime.getTime());

            //测试打印数据
            pojoInfo.setId(id);
            pojoInfo.setPlace_id(placeId);
            pojoInfo.setPlace_name(placeName);
            pojoInfo.setPlace_categoryId(placeCategoryIds);
            pojoInfo.setPlace_categoryName(placeCategoryName);
            pojoInfo.setPlace_categoryIdSingle(placeCategoryIdSingle);
            pojoInfo.setPlace_cityId(placeCityId);
            pojoInfo.setPlace_cityName(placeCityName);
            pojoInfo.setPlace_districtId(placeDistrictId);
            pojoInfo.setPlace_districtName(placeDistrictName);
            pojoInfo.setPlace_lat(placeLat);
            pojoInfo.setPlace_lng(placeLng);
            pojoInfo.setPlace_commentCount(placeCommentCount);
            pojoInfo.setPlace_signupCount(placeSignupCount);
            pojoInfo.setPlace_lowestPrice(placeLowestPrice);
            pojoInfo.setPlace_placeScore(placePlaceScore);
            pojoInfo.setPlace_bizPlaceUrl(placeBizPlaceUrl);
            pojoInfo.setPlace_salePlanId(placeSalePlanId);
            pojoInfo.setPlace_startTime(placeStartTime);
            pojoInfo.setPlace_endTime(placeEndTime);
            pojoInfo.setPlace_isSaled(placeIsSaled);
            pojoInfo.setScore(score);
            pojoInfo.setPlace_dist(placeDist);
            pojoInfo.setPlace_isSigned(placeIsSigned);
            pojoInfo.setPlace_groupId(placeGroupId);
            pojoInfo.setPlace_phone(placePhone);
            pojoInfo.setPlace_address(placeAddress);
            pojoInfo.setPlace_isVip(placeIsVip);
            pojoInfo.setPlace_isShelves(placeIsShelves);
            placeIndexInfoList.add(pojoInfo);

            //封装返回的数据
            PlaceSearchResponse placeRes = new PlaceSearchResponse();

            placeRes.setId(Integer.parseInt(placeId));
            placeRes.setTotalRecord(solrDocumentList.getNumFound());
            placeRes.setName(placeName);
            placeRes.setCityId(placeCityId);
            placeRes.setCityName(placeCityName);
            placeRes.setDistrictId(placeDistrictId);
            placeRes.setDistrictName(placeDistrictName);
            placeRes.setCategoryNames(placeCategoryName);
            placeRes.setLng(placeLng);
            placeRes.setLat(placeLat);
            if (searchType == 1) {
                double distance = DistanceUtil.getDistance(lng, lat, placeLng, placeLat);
                //计算二点距离
                placeRes.setDistance((float) distance);
            } else {
                placeRes.setDistance(placeDist);
            }
            placeRes.setLowestPrice(placeLowestPrice);
            placeRes.setPlaceScore(placePlaceScore);
            placeRes.setCommentCount(placeCommentCount);
            placeRes.setBizPlaceUrl(placeBizPlaceUrl);
            placeRes.setIsSigned(placeIsSigned);
            placeRes.setGroupId(placeGroupId);
            placeRes.setPhone(placePhone);
            placeRes.setAddress(placeAddress);
            placeRes.setIsVip(placeIsVip);
            logger.warn("solr得出的score:" + score);
            if (placeSignupCount != null && placeLowestPrice != null && placeDist != null) {
                //验证score
                Double jisuanScore = getScore(placeSignupCount, placeLowestPrice, placeDist);
                logger.warn("公式计算得出的score=====solr得出score:" + jisuanScore + "=======" + score);
            }
            placeResList.add(placeRes);
        }
        //测试打印数据
        logger.warn("PlaceIndexInfo-size:" + placeIndexInfoList.size());
        logger.warn("PlaceIndexInfo:" + JSON.json(placeIndexInfoList));

        return placeResList;

    }
    private List<PlaceSearchResponse> getPlaceSearchResponseList(SolrDocumentList solrDocumentList, Map<String, Map<String, List<String>>> highlighting) throws ParseException, IOException {
        List<PlaceSearchResponse> placeResList = new ArrayList<PlaceSearchResponse>();
        List<PlaceIndexInfo> placeIndexInfoList = new ArrayList<PlaceIndexInfo>();

        for (SolrDocument solrDocument : solrDocumentList) {
            PlaceIndexInfo pojoInfo = new PlaceIndexInfo();
            //解析solr中数据
            String id = (String) solrDocument.get("id");
            String placeId = (String) solrDocument.get("place_id");
            String placeName = (String) solrDocument.get("place_name");
            List<Integer> placeCategoryIds = (List<Integer>) solrDocument.get("place_categoryId");
            List<String> placeCategoryName = (List<String>) solrDocument.get("place_categoryName");
            Integer placeCategoryIdSingle = (Integer) solrDocument.get("place_categoryIdSingle");
            Integer placeCityId = (Integer) solrDocument.get("place_cityId");
            String placeCityName = (String) solrDocument.get("place_cityName");
            Integer placeDistrictId = (Integer) solrDocument.get("place_districtId");
            String placeDistrictName = (String) solrDocument.get("place_districtName");
            String placeLatLng = (String) solrDocument.get("place_latlng");
            Double placeLat = 0.0;
            Double placeLng = 0.0;
            if (!StringUtil.isBlankOrNull(placeLatLng)) {
                placeLat = Double.parseDouble(placeLatLng.split(",")[0]);
                placeLng = Double.parseDouble(placeLatLng.split(",")[1]);
            }

            Integer placeCommentCount = (Integer) solrDocument.get("place_commentCount");
            Integer placeSignupCount = (Integer) solrDocument.get("place_signupCount");
            Double placeLowestPrice = (Double) solrDocument.get("place_lowestPrice");
            Double placePlaceScore = (Double) solrDocument.get("place_placeScore");
            String placeBizPlaceUrl = (String) solrDocument.get("place_bizPlaceUrl");
            String placeSalePlanId = (String) solrDocument.get("place_salePlanId");
            Integer placeIsSigned = (Integer) solrDocument.get("place_isSigned");
            Date placeStartTime = (Date) solrDocument.get("place_startTime");
            Date placeEndTime = (Date) solrDocument.get("place_endTime");
            Integer placeIsSaled = (Integer) solrDocument.get("place_isSaled");
            String placeGroupId = (String) solrDocument.get("place_groupId");
            Float score = (Float) solrDocument.get("score");
            Float placeDist = (Float) solrDocument.get("place_dist");
            String placePhone = (String) solrDocument.get("place_phone");
            String placeAddress = (String) solrDocument.get("place_address");
            Integer placeIsVip = (Integer) solrDocument.get("place_isVip");
            Integer placeIsShelves = (Integer) solrDocument.get("place_isShelves");
          /*  Map<String, List<String>> stringListMap = highlighting.get(solrDocument.get("id").toString());
            List<String> list = null;*/
            //取高亮显示的结果
            /*if (stringListMap != null && stringListMap.size() > 0) {
                list = stringListMap.get("place_name");
            }
            if (list != null && list.size() > 0) {
                placeName = list.get(0);
            } else {
                placeName = (String) solrDocument.get("place_name");
            }*/

            placeStartTime = placeStartTime == null ? null : CommonUtil.getFormatDateByLong(placeStartTime.getTime());

            placeEndTime = placeEndTime == null ? null : CommonUtil.getFormatDateByLong(placeEndTime.getTime());

            //测试打印数据
            pojoInfo.setId(id);
            pojoInfo.setPlace_id(placeId);
            pojoInfo.setPlace_name(placeName);
            pojoInfo.setPlace_categoryId(placeCategoryIds);
            pojoInfo.setPlace_categoryName(placeCategoryName);
            pojoInfo.setPlace_categoryIdSingle(placeCategoryIdSingle);
            pojoInfo.setPlace_cityId(placeCityId);
            pojoInfo.setPlace_cityName(placeCityName);
            pojoInfo.setPlace_districtId(placeDistrictId);
            pojoInfo.setPlace_districtName(placeDistrictName);
            pojoInfo.setPlace_lat(placeLat);
            pojoInfo.setPlace_lng(placeLng);
            pojoInfo.setPlace_commentCount(placeCommentCount);
            pojoInfo.setPlace_signupCount(placeSignupCount);
            pojoInfo.setPlace_lowestPrice(placeLowestPrice);
            pojoInfo.setPlace_placeScore(placePlaceScore);
            pojoInfo.setPlace_bizPlaceUrl(placeBizPlaceUrl);
            pojoInfo.setPlace_salePlanId(placeSalePlanId);
            pojoInfo.setPlace_startTime(placeStartTime);
            pojoInfo.setPlace_endTime(placeEndTime);
            pojoInfo.setPlace_isSaled(placeIsSaled);
            pojoInfo.setScore(score);
            pojoInfo.setPlace_dist(placeDist);
            pojoInfo.setPlace_isSigned(placeIsSigned);
            pojoInfo.setPlace_groupId(placeGroupId);
            pojoInfo.setPlace_phone(placePhone);
            pojoInfo.setPlace_address(placeAddress);
            pojoInfo.setPlace_isVip(placeIsVip);
            pojoInfo.setPlace_isShelves(placeIsShelves);
            placeIndexInfoList.add(pojoInfo);

            //封装返回的数据
            PlaceSearchResponse placeRes = new PlaceSearchResponse();

            placeRes.setId(Integer.parseInt(placeId));
            placeRes.setTotalRecord(solrDocumentList.getNumFound());
            placeRes.setName(placeName);
            placeRes.setCityId(placeCityId);
            placeRes.setCityName(placeCityName);
            placeRes.setDistrictId(placeDistrictId);
            placeRes.setDistrictName(placeDistrictName);
            placeRes.setCategoryNames(placeCategoryName);
            placeRes.setLng(placeLng);
            placeRes.setLat(placeLat);

            placeRes.setLowestPrice(placeLowestPrice);
            placeRes.setPlaceScore(placePlaceScore);
            placeRes.setCommentCount(placeCommentCount);
            placeRes.setBizPlaceUrl(placeBizPlaceUrl);
            placeRes.setIsSigned(placeIsSigned);
            placeRes.setGroupId(placeGroupId);
            placeRes.setPhone(placePhone);
            placeRes.setAddress(placeAddress);
            placeRes.setIsVip(placeIsVip);
            logger.warn("solr得出的score:" + score);
            if (placeSignupCount != null && placeLowestPrice != null && placeDist != null) {
                //验证score
                Double jisuanScore = getScore(placeSignupCount, placeLowestPrice, placeDist);
                logger.warn("公式计算得出的score=====solr得出score:" + jisuanScore + "=======" + score);
            }
            placeResList.add(placeRes);
        }
        //测试打印数据
        logger.warn("PlaceIndexInfo-size:" + placeIndexInfoList.size());
        logger.warn("PlaceIndexInfo:" + JSON.json(placeIndexInfoList));

        return placeResList;

    }


    public Double getScore(Integer _signupCount, Double _lowerPrice, Float _dist) {
        Integer signupCount = 0;
        Double lowestPrice = 0.0;
        if (Configure.getPropertyBykey("place_signupCount") != null) {
            signupCount = Integer.parseInt(Configure.getPropertyBykey("place_signupCount"));
        }
        if (Configure.getPropertyBykey("place_lowestPrice") != null) {
            lowestPrice = Double.parseDouble(Configure.getPropertyBykey("place_lowestPrice"));
        }
        Float dist = Float.parseFloat(Configure.getPropertyBykey("place_dist"));
        Double jsScore = _signupCount * 1.0 / signupCount + lowestPrice / (1 * _lowerPrice + lowestPrice) + dist / (1 * _dist + dist);
        logger.warn(String.format("%d * 1.0/%d + %f/(1 * %f + %f) + %f/(1*%f + %f) = %f", _signupCount, signupCount, lowestPrice, _lowerPrice, lowestPrice, dist, _dist, dist, jsScore));
        return jsScore;
    }

    private boolean addDocUtil(PlaceIndexInfo indexInfo) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            //创建文档对象
            SolrInputDocument document = new SolrInputDocument();
            String uniqueId = SearchConstants.PLACE_ID_PREFIX + UUID.randomUUID().toString();
            document.addField("id", uniqueId);
            document.addField("place_id", indexInfo.getPlace_id());
            document.addField("place_name", indexInfo.getPlace_name());
            List<Integer> categoryIds = indexInfo.getPlace_categoryId();
            List<String> categoryNames = indexInfo.getPlace_categoryName();
            if (CollectionUtils.isNotEmpty(categoryIds)) {
                for (int i = 0; i < categoryIds.size(); i++) {
                    document.addField("place_categoryId", categoryIds.get(i));
                }
            }
            if (CollectionUtils.isNotEmpty(categoryNames)) {
                for (int i = 0; i < categoryIds.size(); i++) {
                    document.addField("place_categoryName", categoryNames.get(i));
                }
            }
            document.addField("place_categoryIdSingle", indexInfo.getPlace_categoryIdSingle());
            document.addField("place_cityId", indexInfo.getPlace_cityId());
            document.addField("place_cityName", indexInfo.getPlace_cityName());
            document.addField("place_districtId", indexInfo.getPlace_districtId());
            document.addField("place_districtName", indexInfo.getPlace_districtName());
            document.addField("place_latlng", indexInfo.getPlace_lat() + "," + indexInfo.getPlace_lng());


            document.addField("place_commentCount", indexInfo.getPlace_commentCount());
            document.addField("place_signupCount", indexInfo.getPlace_signupCount());
            if (indexInfo.getPlace_lowestPrice() == null) {
                document.addField("place_lowestPrice", -1.00);//如果没有价格就存-1 用于价格排序
            } else {
                document.addField("place_lowestPrice", indexInfo.getPlace_lowestPrice());
            }

            document.addField("place_placeScore", indexInfo.getPlace_placeScore());
            document.addField("place_bizPlaceUrl", indexInfo.getPlace_bizPlaceUrl());
            document.addField("place_isSigned", indexInfo.getPlace_isSigned());
            document.addField("place_phone", indexInfo.getPlace_phone());
            document.addField("place_address", indexInfo.getPlace_address());
            if (!StringUtil.isBlankOrNull(indexInfo.getPlace_salePlanId()) && !"0".equals(indexInfo.getPlace_salePlanId()))
                document.addField("place_salePlanId", indexInfo.getPlace_salePlanId());
            if (indexInfo.getPlace_startTime() != null)
                document.addField("place_startTime", CommonUtil.getSolrDate(indexInfo.getPlace_startTime()));
            if (indexInfo.getPlace_endTime() != null)
                document.addField("place_endTime", CommonUtil.getSolrDate(indexInfo.getPlace_endTime()));
            //1 不可售卖 2 可以售卖 0没有销售计划
            document.addField("place_isSaled", indexInfo.getPlace_isSaled());
            //1上架  2下架  不传全包含
            document.addField("place_isShelves", indexInfo.getPlace_isShelves());
            document.addField("place_groupId", indexInfo.getPlace_groupId());
            List<String> initialsList = indexInfo.getPlace_initials();
            if (CollectionUtils.isNotEmpty(initialsList)) {
                for (int i = 0; i < initialsList.size(); i++) {
                    document.addField("place_initials", initialsList.get(i));
                }
            }
            document.addField("place_isVip", indexInfo.getPlace_isVip());
            solrServer.add(document);
            solrServer.commit();
            logger.info("添加场馆索引成功");
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加场馆索引失败", e);
            return false;
        }
    }
}
